<template>

  <slot :showValue="showValue"></slot>
  <template v-if="!useSlotDefault">
    <van-field v-model="showValue" :label="label" :placeholder="placeholder" @click="onShow" :rules="rules" readonly/>
  </template>

  <van-popup v-model:show="display"  position="bottom">
    <van-picker
        :title="label"
        :columns="columns"
        :columns-field-names="{text: 'label'}"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChange"
    />
  </van-popup>

</template>

<script setup>
import {computed, watch, ref, reactive, useSlots} from "vue";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => ([])
  },
  placeholder: {
    type: String,
    default: () => '请选择'
  },
  label: {
    type: String,
    default: () => '标签'
  },
  columns: {
    type: Array,
    default: () => ([])
  },
  rules: {
    type: Array,
    default: () => ([])
  }
})

const value = ref(null)
const showValue = ref(null)

const display = ref(false)

const useSlotDefault = !!useSlots().default

const emits = defineEmits(['update:modelValue'])

const toValue = (value) => {
    return [value.value]
}

const toItem = (value) => {
  let items = []

  for (let index in value) {
    let item = value[index]

    for (let index0 in props.columns) {
      let item0 = props.columns[index0]
      if (item == item0.value) {
        items.push(item0)
        break
      }
    }

  }

  return items
}

const onShow = () => {
  display.value = true
}

const onConfirm = (index) => {
  const value = toValue(index)
  emits('update:modelValue', value)
  onCancel()
}

const onCancel = () => {
  display.value = false
}

const onChange = () => {

}

const cb = () => {
  value.value = props.modelValue
  showValue.value = toItem(value.value).map((item) => item.label).join(',')
}

cb()
watch(() => props.columns, cb)
watch(() => props.modelValue, cb)

const show = () => {
  onShow()
}

defineExpose({
  show
})

</script>

<style scoped>

</style>